<!-- ----------------------------
--  @author: 野狼上校           --
--  @create: 2024-07-17 10:06  --
--  @version: 1.0              --
-------------------------------->
<!-- 设备管理 -->

<template>
  <el-breadcrumb :separator-icon="DArrowRight" style='font: normal bold 1.1rem "Fira Sans", serif;'>
    <el-breadcrumb-item v-for="(item, index) in items" :key="index">{{ item }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-divider/>
  <!--  查询条件  -->
  <el-row :gutter="20" class="my-query">
    <el-col :span="6">
    </el-col>
    <el-col :span="8">
      <el-input placeholder="请输入公司名称" v-model="queryForm.companyName" clearable/>
    </el-col>
    <el-col :span="4">
      <el-button type="primary" :icon="Search" @click="initDevicesData">查询</el-button>
    </el-col>
    <el-col :span="6">
    </el-col>
  </el-row>

  <!-- 列表数据 -->
  <el-row :gutter="20" class="my-table">
    <el-col :span="4">
      设备列表
    </el-col>
    <el-col :span="16">
    </el-col>
    <el-col :span="4">
      <el-button type="success" :icon="Plus" @click="addDeviceHandler">新增设备</el-button>
    </el-col>
  </el-row>

  <!--  表格数据  -->
  <el-table :data="devices" stripe border style="width: 100%">
    <el-table-column prop="companyName" label="公司名称" width="100" align="center"/>
    <el-table-column prop="productLine" label="生产产线" width="120" align="center"/>
    <el-table-column prop="machineName" label="机床名称" width="120" align="center"/>
    <el-table-column prop="deviceGuid" label="设备Id" width="120" align="center"/>
<!--    <el-table-column prop="machineStatus" label="机床运行状态" width="120" align="center">
      <template #default="{row}">
        &lt;!&ndash; 当 deviceStatus 为 0 时 &ndash;&gt;
        <el-tag v-if="row.machineStatus === 0" size="large" type="danger">
          <span>停止</span>
        </el-tag>
        &lt;!&ndash; 当 deviceStatus 为 1 时 &ndash;&gt;
        <el-tag v-else-if="row.machineStatus === 1" size="small" type="success">
          <span>运行</span>
        </el-tag>
        &lt;!&ndash; 如果需要处理其他情况（可选） &ndash;&gt;
        <el-tag v-else size="small" type="info">
          <span>未知状态</span>
        </el-tag>
      </template>
    </el-table-column>-->

    <el-table-column prop="deviceOnline" label="设备在线状态" width="120" align="center">
      <template #default="{row}">
        <!-- 当 deviceStatus 为 0 时 -->
        <el-tag v-if="row.deviceOnline === 0" size="large" type="danger">
          <span>离线</span>
        </el-tag>
        <!-- 当 deviceStatus 为 1 时 -->
        <el-tag v-else-if="row.deviceOnline === 1" size="small" type="success">
          <span>在线</span>
        </el-tag>
        <!-- 如果需要处理其他情况（可选） -->
        <el-tag v-else size="small" type="info">
          <span>未知状态</span>
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="alarmStatus" label="报警状态" width="120" align="center">
      <template #default="{row}">
        <!-- 当 deviceStatus 为 0 时 -->
        <el-tag v-if="row.alarmStatus === 0" size="large" type="danger">
          <span>关闭</span>
        </el-tag>
        <!-- 当 deviceStatus 为 1 时 -->
        <el-tag v-else-if="row.alarmStatus === 1" size="small" type="success">
          <span>开启</span>
        </el-tag>
        <!-- 如果需要处理其他情况（可选） -->
        <el-tag v-else size="small" type="info">
          <span>未知状态</span>
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="warn" label="预警值" width="120" align="center">
      <template #default="{row}">
        <span>{{row.xWarn}} - {{row.yWarn}} - {{row.zWarn}}</span>
      </template>
    </el-table-column>

    <el-table-column prop="alarm" label="报警值" width="120" align="center">
      <template #default="{row}">
        <span>{{row.xAlarm}} - {{row.yAlarm}} - {{row.zAlarm}}</span>
      </template>
    </el-table-column>


<!--    <el-table-column prop="updateTime" label="更新时间" width="120" align="center"/>-->
    <el-table-column prop="createTime" label="创建时间" width="120" align="center"/>


    <el-table-column prop="action" label="操作" min-width="300px" fixed="right" align="center">
      <template v-slot="scope">
        <!--     查看详情     -->
        <el-button size="small" type="primary" :icon="Search" @click="descDeviceHandler(scope.row.deviceGuid)">查看</el-button>
        <!--     修改     -->
        <el-button size="small" type="primary" :icon="Edit" @click="editDeviceHandler(scope.row)">修改</el-button>
        <!--     设置阈值     -->
        <el-button size="small" type="primary" :icon="Setting" @click="setDeviceThresholdHandler(scope.row)">设置阈值</el-button>
        <!--    设备运行状态（定时任务开启状态）    -->
        <el-button size="small" v-if="scope.row.deviceWorking === 0" type="primary" :icon="Setting"
                   @click="deviceRunOperateHandler(scope.row.deviceGuid,1)">运行
        </el-button>
        <el-button size="small" v-else-if="scope.row.deviceWorking === 1" type="primary" :icon="Setting"
                   @click="deviceRunOperateHandler(scope.row.deviceGuid,0)">停止
        </el-button>
        <!--     预警设置  -->
        <el-button size="small" v-if="scope.row.alarmStatus === 0" type="primary" :icon="Setting"
                   @click="alarmOperateHandler(scope.row.deviceGuid,1)">开启预警
        </el-button>
        <el-button size="small" v-else-if="scope.row.alarmStatus === 1" type="primary" :icon="Setting"
                   @click="alarmOperateHandler(scope.row.deviceGuid,0)">关闭预警
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--  分页插件  -->
  <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      class="el-pagination"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 新增 -->
  <AddDevice v-model="dialogAddDeviceVisible" :dialogAddDeviceVisible="dialogAddDeviceVisible"
             @initDevicesData="initDevicesData"/>
  <!-- 修改 -->
  <EditDevice v-model="dialogEditDeviceVisible" :dialogEditDeviceVisible="dialogEditDeviceVisible"
              :deviceRowInfo="deviceRowInfo" @initDevicesData="initDevicesData"/>

  <!-- 设置阈值 -->
  <SetThreshold v-model="dialogSetThresholdVisible" :dialogSetThresholdVisible="dialogSetThresholdVisible"
                :deviceRowInfo="deviceRowInfo" @initDevicesData="initDevicesData"/>
</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
import {DArrowRight, Edit, Plus, Search, Setting} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {SUCCESS} from "@/utils/constants.ts";
import AddDevice from "@/views/system/device/add.vue"
import EditDevice from "@/views/system/device/edit.vue"
import {RespResult} from "@/api";
import {createDeviceQuartz, getDevicesByPage, pauseDeviceQuartz} from "@/api/auth/device.ts";
import SetThreshold from "@/views/system/device/setThreshold.vue";
import {setAlarmOperate} from "@/api/crash/alarmRecord.ts";
import router from "@/router";

const breadcrumb: any = useRoute().meta.title;
const items: string[] = breadcrumb.split(",");

/*查询条件*/
const queryForm = ref({
  companyName: ""
});

/*表格数据*/
const devices = ref([]);

/*分页条件*/
const pagination = ref({
  pageNum: 1,
  pageSize: 10
})
/*总记录数*/
const total = ref(0);
/*改变每页显示数量*/
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize
  initDevicesData();
}
/*改变页码*/
const handleCurrentChange = (pageNum: number) => {
  pagination.value.pageNum = pageNum;
  initDevicesData();
}

/*初始化表格数据*/
onMounted(() => {
  initDevicesData();
})
const initDevicesData = async () => {
  //发送请求
  await getDevicesByPage({
    pageSize: pagination.value.pageSize,
    pageNum: pagination.value.pageNum,
    companyName: queryForm.value.companyName
  }).then(
      (response: RespResult) => {
        if (response.code === SUCCESS) {
          const jsonObject = JSON.parse(response.data);
          devices.value = jsonObject.records;
          total.value = jsonObject.total;
        } else {
          ElMessage({
            message: "获取数据失败",
            type: 'error'
          })
        }
      }
  )
}

/*新增*/
const dialogAddDeviceVisible = ref(false);
const addDeviceHandler = () => {
  //显示弹出框
  dialogAddDeviceVisible.value = true;
}

/*修改*/
const dialogEditDeviceVisible = ref(false);
const deviceRowInfo = ref({})
const editDeviceHandler = (row: any) => {
  //显示弹出框
  dialogEditDeviceVisible.value = true;
  deviceRowInfo.value = row;
}

/*详情*/
const descDeviceHandler = (deviceGuid: string) => {
  router.push({path: "/deviceDesc", query: {deviceGuid: deviceGuid}});
}

/*设置阈值*/
const dialogSetThresholdVisible = ref(false);
const setDeviceThresholdHandler = (row: any) => {
  //显示弹出框
  dialogSetThresholdVisible.value = true;
  deviceRowInfo.value = row;
}

/*设备运行状态设置*/
const deviceRunOperateHandler = (deviceGuid: string, operateType: number) => {
  if(operateType == 0){
    pauseDeviceQuartz({
      deviceGuid: deviceGuid
    }).then(
        (response: RespResult) => {
          if (response.code === SUCCESS) {
            // 重新加载
            initDevicesData()
            ElMessage({
              message: "操作成功",
              type: 'success'
            })
          } else {
            ElMessage({
              message: "操作失败",
              type: 'error'
            })
          }
        }
    )
  } else if(operateType == 1){
    createDeviceQuartz({
      deviceGuid: deviceGuid
    }).then(
        (response: RespResult) => {
          if (response.code === SUCCESS) {
            // 重新加载
            initDevicesData()
            ElMessage({
              message: "操作成功",
              type: 'success'
            })
          } else {
            ElMessage({
              message: "操作失败",
              type: 'error'
            })
          }
        }
    )
  }else {
    ElMessage({
      message: "参数错误",
      type: 'error'
    })
  }

}

/*预警设置*/
const alarmOperateHandler = (deviceGuid: string, operateType: number) => {
  setAlarmOperate({
    deviceGuid: deviceGuid,
    operateType: operateType
  }).then(
      (response: RespResult) => {
        if (response.code === SUCCESS) {
          // 重新加载
          initDevicesData()
          ElMessage({
            message: "操作成功",
            type: 'success'
          })
        } else {
          ElMessage({
            message: "操作失败",
            type: 'error'
          })
        }
      }
  )
}


</script>

<style scoped>
.my-query {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin-bottom: 20px;
  padding-top: 15px;
  padding-bottom: 15px;
  border: 1px solid #DDDDDD;
  box-sizing: border-box;
}

.my-table {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin-bottom: 5px;
  padding-top: 15px;
  padding-bottom: 15px;
  border: 1px solid #DDDDDD;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

</style>